package com.ckzp.jfinal.base;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ckzp.core.ConfigUtil;
import com.ckzp.core.Results;
import com.ckzp.core.json.Jmode;
import com.ckzp.core.json.JsonResult;
import com.ckzp.core.json.JsonUtil;
import com.ckzp.core.lc.Aes;
//import com.ckzp.core.lc.HutoolRsa;
import com.ckzp.core.model.Datas;
import com.ckzp.core.util.HtmlUtil;
import com.ckzp.core.util.JwtUtil;
import com.ckzp.core.util.StringUtil;
import com.ckzp.jfinal.base.csrf.TokenService;
import com.ckzp.jfinal.form.FormData;
import com.ckzp.jfinal.system.model.SysUser;
import com.ckzp.jfinal.system.WebSite;
import com.jfinal.core.Controller;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Model;

import java.util.Date;
import java.util.Map;

/**
 * Created by 51594 on 2022/7/27.
 */
public class BaseController extends Controller {


    protected Log log = Log.getLog(Controller.class);


    private static final String PRIVATE_KEY = ConfigUtil.getProperty("PRIVATE_KEY");
    //private static final String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAI32uExEDKLNwyLtZ4etxTUigdxCw61/rzv2x/B3WrzCEOzituXOvCZq7WCKJFKN9QmJB2pL5LUS5V8iinFN1D/Csh7puPTIkwSoY4jzoa5KiudfjJYvuJzNLSxGA7T9c+aOnB+rbwiGnqW/+ji4x9Sp04VJfgJJlazxVYvg2/DXAgMBAAECgYEAhwRRf+dwhR5hKsTTpEz2tHRfQZcV99rqVIN+4QsC92czJbjx7lrSw08K+Lgpl4J/vFPhA42utTCFiheVx/EXnR9tspBxlZDP7wMEY+/xoMz7oI0NcUjwoxNWvkwRVgCgxHJaWsOfV/0Ksq8lwDMRY1LShpCK1+kLyV18C13GvUECQQDycfSBzmIKP4mphjYWiH2hcSkspvwTkEYATlCoOzHvSkIecztidIux+KH3p6LmXb+3RsrLkrb20o7m+IiNQT6HAkEAleaazVziTDkDukTeqYW3BSHebdnreLNf/gJtbxxhTYAT1AbDx/BcZhryc2zyn8yelgxyllv11kqelN4nyFZ/MQJAFHJF05irLgATxQc7koTqS242sbxXb/Lv5GC2bqmnWW3iy5yeOnxnt5enWTJ7C4CGhZdjzO1Pnts9D/+PzJHfCwJBAI0PfQ1UIwBnhsJ6nK4aTqhdvtrQ/22OHv8BecndgxNTO1WDKCm2Xr0XDqDgHVGTVIkPHaWw1B7cCW89v2IfQ4ECQAOf8+OOv9LjnC07GZbTgw+IxKuNlyvwISrsB3O/skyLrX7UWMUno917b7HeiPnhcUk3Fmghjc8nv8MyrNEc0Ew=";


    /**
     *
     */
    public static final String MSG_ADD = "添加";
    /**
     *
     */
    public static final String MSG_EDIT = "修改";
    /**
     *
     *
     */
    public static final String MSG_DEL = "删除";
    /**
     *
     */
    protected String SQL = "";

    /**
     *
     */
    public static boolean DEBUG = ConfigUtil.DEBUG();

    /**
     * 权限
     *
     * @param roles
     */
    public void ValidateRole(String roles) {
        renderText("没有权限");
    }

    /**
     * 权限
     *
     * @param roles
     */
    public void ValidateRoleJson(String roles) {
        renderJson(JsonResult.n(93, ""));
    }


    /**
     * @param model
     * @param keyid
     * @param colums
     * @param msg
     * @return
     */
    protected JsonResult DoBasePub(Model model, Object keyid, String colums, String msg) {
        Model bm = model.findById(keyid);
        if (bm != null) {
            if (bm.getInt(colums) == null) {
                return JsonResult.n(9, "字段" + colums + "不存在");
            } else if (bm.getInt(colums) == 0) {
                if (bm.set(colums, 1).update()) {
                    return JsonResult.n(0, msg + "成功");
                } else {
                    return JsonResult.n(9, msg + "失败");
                }
            } else {
                if (bm.set(colums, 0).update()) {
                    return JsonResult.n(0, "取消成功");
                } else {
                    return JsonResult.n(9, "取消失败");
                }
            }
        } else {
            return JsonResult.n(9, "信息不存在");
        }
    }

    /**
     * @param model
     * @param keyid
     * @param msg
     * @return
     */
    protected JsonResult VerifyKey(Model model, Object keyid, String msg) {
        Model bm = model.findById(keyid);
        if (bm == null) {
            return JsonResult.n(0, msg + "不存在");
        } else {
            return JsonResult.n(9, msg + "已存在,不能重复");
        }
    }


    /**
     * @param model
     * @param keyid
     * @param colums
     * @param msg
     * @return
     */
    protected JsonResult DoBasePub(Model model, Object keyid, Object keyid2, String colums, String msg) {
        Model bm = model.findByIds(keyid, keyid2);
        if (bm != null) {
            if (bm.getInt(colums) == 0) {
                if (bm.set(colums, 1).update()) {
                    return JsonResult.n(0, msg + "成功");
                } else {
                    return JsonResult.n(9, msg + "失败");
                }
            } else {
                if (bm.set(colums, 0).update()) {
                    return JsonResult.n(0, "取消成功");
                } else {
                    return JsonResult.n(9, "取消失败");
                }
            }
        } else {
            return JsonResult.n(9, "信息不存在");
        }
    }


    /**
     * @param model
     * @param field
     * @param value
     * @param key_id
     * @return
     */
    protected JsonResult ModifyFieldApi(Model model, String field, String value, Object... key_id) {
        Model o = model.findByIds(key_id);
        if (o != null) {
            boolean result = o.set(field, value).update();
            if (result) {
                return JsonResult.n(0, "修改成功");
            } else {
                return JsonResult.n(9, "修改失败");
            }
        } else {
            return JsonResult.n(9, "信息不存在");
        }
    }

    /**
     * @param model
     * @param keyid
     * @param colums
     * @param msg
     * @return
     */
    protected JsonResult DoBasePubs(Model model, String colums, String msg, Object... keyid) {
        Model bm = model.findByIds(keyid);
        if (bm != null) {
            if (bm.getInt(colums) == 0) {
                if (bm.set(colums, 1).update()) {
                    return JsonResult.n(0, msg + "成功");
                } else {
                    return JsonResult.n(9, msg + "失败");
                }
            } else {
                if (bm.set(colums, 0).update()) {
                    return JsonResult.n(0, "取消成功");
                } else {
                    return JsonResult.n(9, "取消失败");
                }
            }
        } else {
            return JsonResult.n(9, "信息不存在");
        }
    }

    /**
     * JSON 转map
     *
     * @param json
     * @return
     */
    protected Map getMap(String json) {
        return JsonUtil.json2Map(json);
    }

    /**
     * JSON 转map
     *
     * @param json
     * @return
     */
    protected Datas getDatas(String json) {
        return JsonUtil.json2Datas(json);
    }


    /**
     * JSON 转map
     *
     * @return
     */
    protected Datas getDatas() {
        Datas d = null;
        String postdata = getPara("postdata");
        String rawdata = getRawData();
        if (StrUtil.isNotBlank(postdata)) {
            d = JsonUtil.json2Datas(postdata);
        }
        if ((d == null || d.isEmpty()) && StrUtil.isNotBlank(rawdata)) {
            d = JsonUtil.json2Datas(rawdata);
        }
        if (d == null) d = Datas.n();
        return d;
    }


    /**
     * JSON 转map
     *
     * @return
     */
    protected Datas getSecretDatas() {
        String secret = getParaStr("parastr", "");
        if (StrUtil.isBlank(secret)) secret = getRawData();
        if (StrUtil.isNotBlank((secret))) {
            secret = cn.hutool.core.codec.Base64.decodeStr(secret);
            String html = Aes.aesDecrypt(secret);
            return JsonUtil.json2Datas(html);
        }
        return Datas.n();
    }

    /**
     * 从map中取值
     * 产生异堂时抛出巩异常
     *
     * @param m
     * @param para
     * @return
     */
    protected int getInt(Map m, String para) {
        return Integer.parseInt(String.valueOf(m.get(para)));
    }

    /**
     * 从map中取值
     * 产生异堂时抛出巩异常
     *
     * @param m
     * @param para
     * @return
     */
    protected double getDouble(Map m, String para) {
        return Double.parseDouble(String.valueOf(m.get(para)));
    }


    /**
     * 从map中取值
     * 产生异堂时抛出巩异常
     *
     * @param m
     * @param def
     * @return
     */
    protected double getDouble(Double m, double def) {
        return m == null ? def : (m.doubleValue());
    }

    /**
     * 从map中取值
     * 产生异堂时抛出巩异常
     *
     * @param m
     * @param para
     * @return
     */
    protected double getDouble(Map m, String para, double defvalue) {
        try {
            return getDouble(m, para);
        } catch (Exception e) {
            return defvalue;
        }
    }

    /**
     * 从map中取值
     * 产生异堂时反回默认值
     *
     * @param m
     * @param para
     * @return
     */
    protected int getInt(Map m, String para, int defvalue) {
        try {
            return getInt(m, para);
        } catch (Exception e) {
            return defvalue;
        }
    }

    /**
     * 从map中取值
     * 产生异堂时抛出巩异常
     *
     * @param m
     * @param para
     * @return
     */
    protected String getStr(Map m, String para) {
        String values = String.valueOf(m.get(para));
        if (values == null) return null;
        values = HtmlUtil.toHtmlInput(values);
        //values = Jsoup.clean(values, Whitelist.basicWithImages());
        return values;
    }

    /**
     * 从map中取值
     * 产生异堂时反回默认值
     *
     * @param m
     * @param para
     * @return
     */
    protected String getStr(Map m, String para, String defvalue) {
        try {
            String values = getStr(m, para);
            if (values == null) values = defvalue;
            return values;
        } catch (Exception e) {
            return defvalue;
        }
    }

    /**
     * 从map中取值
     * 产生异堂时抛出巩异常
     *
     * @param m
     * @param para
     * @return
     */
    protected String getStr(Model m, String para) {
        return getStr(m, para, null);
    }

    /**
     * 从map中取值
     * 产生异堂时反回默认值
     *
     * @param m
     * @param para
     * @return
     */
    protected String getStr(Model m, String para, String defvalue) {
        try {

            return m.getStr(para) == null ? defvalue : m.getStr(para);
        } catch (Exception e) {
            return defvalue;
        }
    }


    /**
     * 字符转数字
     * 产生异堂时反回默认值
     *
     * @param para
     * @return
     */
    protected int getInt(String para, int defvalue) {
        try {
            return getInt(para);
        } catch (Exception e) {
            return defvalue;
        }
    }

    /**
     * 字符转数字
     * 产生异堂时反回默认值
     *
     * @param str
     * @return
     */
    protected String getStr(String str, String defvalue) {
        return str == null ? defvalue : str;
    }

    /**
     * 字符转数字
     * 产生异堂时反回默认值
     *
     * @param para
     * @return
     */
    protected int getParaInt(String para, int defvalue) {
        try {
            Integer v = getParaToInt(para);
            return v == null ? defvalue : v.intValue();
        } catch (Exception e) {
            return defvalue;
        }
    }


    protected int getSecretParaInt(String para, int defvalue) {
        String secret = getParaStr("parastr", "");
        if (StrUtil.isBlank(secret)) secret = getRawData();
        if (StrUtil.isNotBlank((secret))) {
            secret = cn.hutool.core.codec.Base64.decodeStr(secret);
            secret = Aes.aesDecrypt(secret);
            Datas datas = JSONUtil.toBean(secret, Datas.class);
            return datas.getInt(para, defvalue);
        } else {
            if (ConfigUtil.isWindows()) {
                return getInt(para, defvalue);
            } else {
                return defvalue;
            }
        }
    }


    protected long getSecretParaLong(String para, long defvalue) {
        String secret = getParaStr("parastr", "");
        if (StrUtil.isBlank(secret)) secret = getRawData();
        if (StrUtil.isNotBlank((secret))) {
            secret = cn.hutool.core.codec.Base64.decodeStr(secret);
            secret = Aes.aesDecrypt(secret);
            System.out.println(secret);
            Datas datas = JSONUtil.toBean(secret, Datas.class);
            return datas.getLong(para, defvalue);
        } else {
            if (ConfigUtil.isWindows()) {
                return getParaLong(para, defvalue);
            } else {
                return defvalue;
            }
        }
    }

    /**
     * @param para
     * @param defvalue
     * @return
     */
    protected String getSecretParaStr(String para, String defvalue) {
        String secret = getParaStr("parastr", "");
        if (StrUtil.isBlank(secret)) secret = getRawData();
        if (StrUtil.isNotBlank((secret))) {
            secret = cn.hutool.core.codec.Base64.decodeStr(secret);
            secret = Aes.aesDecrypt(secret);
            System.out.println(secret);
            Datas datas = JSONUtil.toBean(secret, Datas.class);
            return datas.getStr(para, defvalue);
        } else {
            if (ConfigUtil.isWindows()) {
                return getParaStr(para, defvalue);
            } else {
                return defvalue;
            }
        }
    }


    protected Datas getSecretParaData(String para, Datas defvalue) {
        String secret = getParaStr("parastr", "");
        if (StrUtil.isBlank(secret)) secret = getRawData();
        if (StrUtil.isNotBlank((secret))) {
            secret = cn.hutool.core.codec.Base64.decodeStr(secret);
            Datas datas = JSONUtil.toBean(Aes.aesDecrypt(secret), Datas.class);
            return datas.getDatas(para);
        } else {
            if (ConfigUtil.isWindows()) {
                return getDatas(para);
            } else {
                return defvalue;
            }
        }
    }

    protected Object getSecretPara(String para) {
        String secret = getParaStr("parastr", "");
        if (StrUtil.isBlank(secret)) secret = getRawData();
        if (StrUtil.isNotBlank((secret))) {
            secret = cn.hutool.core.codec.Base64.decodeStr(secret);
            secret = Aes.aesDecrypt(secret);
            System.out.println(secret);
            Datas datas = JSONUtil.toBean(secret, Datas.class);
            return datas.get(para);
        } else {
            return get(para);
        }
    }

    /**
     * 字符转数字
     * 产生异堂时反回默认值
     *
     * @param para
     * @return
     */
    protected long getParaLong(String para, long defvalue) {
        try {
            Long v = getParaToLong(para);
            return v == null ? defvalue : v.longValue();
        } catch (Exception e) {
            return defvalue;
        }
    }

    /**
     * 用request中取值
     * 产生异堂时反回默认值
     *
     * @param para
     * @return
     */
    protected String getParaStr(String para, String defvalue) {
        String values = getPara(para);
        if (values == null) return defvalue;
        //values = HtmlUtil.decode(values);
        //values = Jsoup.clean(values, Whitelist.basicWithImages());
        return getStr(values, defvalue);
    }


    /**
     * 用request中取值
     * 产生异堂时反回默认值
     *
     * @param para
     * @return
     */
    protected double getParaDouble(String para, double defvalue) {
        try {
            Double v = Double.parseDouble(getParaStr(para, ""));
            return v == null ? defvalue : v.doubleValue();
        } catch (Exception e) {
            return defvalue;
        }
    }

    /**
     * 用request中取值
     * 产生异堂时反回默认值
     *
     * @param para
     * @return
     */
    protected Datas getParaData(String para, String defvalue) {
        String values = getPara(para);
        if (values == null) values = defvalue;
        return JsonUtil.json2Datas(getStr(values, defvalue));
    }

    /**
     * 用request中取值
     * 产生异堂时反回默认值
     *
     * @return
     */
    protected Datas getRawData(String defvalue) {
        String values = getRawData();
        if (values == null) values = defvalue;
        return JsonUtil.json2Datas(getStr(values, defvalue));
    }

    /**
     * 用request中取值
     * 产生异堂时反回默认值
     *
     * @param para
     * @return
     */
    protected Date getParaDate(String para, Date defvalue) {
        try {
            return getParaToDate(para);
        } catch (Exception e) {
            return defvalue;
        }
    }

    /**
     * 用request中取值
     * 产生异堂时反回默认值
     *
     * @param para
     * @return
     */
    protected Date getParaDate(String para) {
        return getParaDate(para, null);
    }

    /**
     * @param fd
     */
    protected void setForm(FormData fd) {
        if (fd == null) fd = FormData.dao();
        setAttr("form", fd);
    }


    /**
     * \
     *
     * @param o
     * @return
     */
    protected String toJsonStr(Object o) {
        return JsonUtil.toJsonString(o);
    }

    /**
     * @param result
     * @param msg
     * @return
     */
    protected JsonResult Json(boolean result, String msg) {
        if (result) {
            return JsonResult.n(0, msg + "成功", this);
        } else {
            return JsonResult.n(9, msg + "失败", this);
        }//
    }


    /**
     * 批量删除
     */
    public JsonResult DelMoreModel(Model model, String keys, String msg) {
        ///////////////////////////////////
        int succ = 0, error = 0;
        String[] ids = StringUtil.split(keys, ",");
        for (String id : ids) {
            if (model.deleteById(id)) {
                succ++;
            } else {
                error++;
            }
        }
        return JsonResult.n(0, msg + "【共删除成功 " + succ + ",失败 " + error + "】");
    }


    /**
     * 批量删除
     */
    public JsonResult DelMoreModelTag(Model model, String keys, String msg) {
        ///////////////////////////////////
        int succ = 0, error = 0;
        String[] ids = StringUtil.split(keys, ",");
        for (String id : ids) {
            Model mod = model.findById(id);
            if (mod != null && mod.set("del_tag", 1).update()) {
                succ++;
            } else {
                error++;
            }
        }
        return JsonResult.n(0, msg + "【共删除成功 " + succ + ", 失败" + error + "】");
    }

    /**
     * @return
     */
    protected int getPage() {
        return getParaToInt("page", 1);
    }

    /**
     * @return
     */
    protected int getLimit() {
        return getParaToInt("limit", 10);
    }

    /**
     * @param limits
     * @return
     */
    protected int getLimit(int limits) {
        return getParaToInt("limit", limits);
    }

    /**
     * @return
     */
    protected int getEmpID() {
        String jwt = WebSite.getJwt(getRequest());
        Results results = JwtUtil.validateJWT(jwt);
        if (results.getCode() == 0) {
            JwtUtil.JwtSubject js = results.getObject(JwtUtil.JwtSubject.class);
            return js.getUserid();
        }
        return 0;
    }

    /**
     * @return
     */
    protected int getBraID() {
        String jwt = WebSite.getJwt(getRequest());
        Results results = JwtUtil.validateJWT(jwt);
        if (results.getCode() == 0) {
            JwtUtil.JwtSubject js = results.getObject(JwtUtil.JwtSubject.class);
            return js.getOrgid();
        }
        return 0;
    }

    /**
     * @return
     */
    protected String getLoginId() {
        String jwt = WebSite.getJwt(getRequest());
        Results results = JwtUtil.validateJWT(jwt);
        if (results.getCode() == 0) {
            JwtUtil.JwtSubject js = results.getObject(JwtUtil.JwtSubject.class);
            return js.getUsername();
        }
        return "";
    }

    /**
     * @return
     */
    protected String getUserName() {
        int emp_id = getEmpID();
        SysUser user = SysUser.dao.findById(emp_id);
        if (user != null) {
            return user.mod.getStr("user_name", "");
        }
        return "";
    }

    /**
     * @return
     */
    protected String getEmpIds() {
        String jwt = WebSite.getJwt(getRequest());
        Results results = JwtUtil.validateJWT(jwt);
        if (results.getCode() == 0) {
            JwtUtil.JwtSubject js = results.getObject(JwtUtil.JwtSubject.class);
            return String.valueOf(js.getUserid());
        }
        return "0";
    }

    /**
     * @return
     */
    protected int getDeptID() {
        String jwt = WebSite.getJwt(getRequest());
        Results results = JwtUtil.validateJWT(jwt);
        if (results.getCode() == 0) {
            JwtUtil.JwtSubject js = results.getObject(JwtUtil.JwtSubject.class);
            return js.getDeptid();
        }
        return 0;
    }


    /**
     * 取得用用所有角色 字符串
     *
     * @return
     */
    protected String getUserRoles() {
        String jwt = WebSite.getJwt(getRequest());
        Results results = JwtUtil.validateJWT(jwt);
        if (results.getCode() == 0) {
            JwtUtil.JwtSubject js = results.getObject(JwtUtil.JwtSubject.class);
            return js.getRoles();
        }
        return "";
    }

    /**
     * 判断用户是否有该权限 字符串
     *
     * @return
     */
    protected boolean hasRole(String roleid) {
        String jwt = WebSite.getJwt(getRequest());
        Results results = JwtUtil.validateJWT(jwt);
        if (results.getCode() == 0) {
            JwtUtil.JwtSubject js = results.getObject(JwtUtil.JwtSubject.class);
            String roles = "|" + js.getRoles() + "|";
            if (roles.indexOf("|" + roleid + "|") > -1) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param jwt
     * @return
     */
    public static Results validateJwt(String jwt) {
        if ("test".equals(jwt)) {
            JwtUtil.JwtSubject js = new JwtUtil.JwtSubject();
            js.setPid(1234);
            js.setUserid(1234);
            js.setUsername("测试");
            Results result = new Results(0);
            result.setCode(0);
            result.setMsg("验证成功");
            result.setMessage("");
            result.setObject(js);
            return result;
        }
        return JwtUtil.validateJWT(jwt);
    }

    /**
     * @param result
     * @return
     */
    public static JwtUtil.JwtSubject getJwt(Results result) {
        try {
            return result.getObject(JwtUtil.JwtSubject.class);
        } catch (Exception e) {
            return new JwtUtil.JwtSubject();
        }
    }

    /**
     * 从jwt中取pid
     *
     * @return
     */
    protected int getJwtPid() {
        return JwtUtil.getJwtInfo(getParaStr("jwt", "")).getPid();
    }

    /**
     * 从jwt中取uid
     *
     * @return
     */
    protected int getJwtUid() {
        return JwtUtil.getJwtInfo(getParaStr("jwt", "")).getUserid();
    }

    /**
     * @return
     */
    protected String getEmpIdStr() {
        return String.valueOf(getEmpID());
    }

    /**
     * @param results
     * @return
     */
    protected Results setToken(Results results) {
        new TokenService().createToken(this);
        return results.setCode(999).setMsg(results.getMsg()).addData("errors", results.getMsg()).addData("token_name", String.valueOf(getAttr("token_name"))).addData("token_value", String.valueOf(getAttr("token_value")));
    }
}